package com.jams.goodox.activity.qa.parent;

import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.BuildConfig;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.home.HomeActivity;
import com.jams.goodox.activity.login.RoleInfoUploadActivity;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.PhotoSelectUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.ActionSheetDialog;
import com.jams.goodox.widget.ActionSheetDialog.OnSheetItemClickListener;
import com.jams.goodox.widget.ActionSheetDialog.SheetItemColor;

import org.json.JSONObject;

/**
 *
 * @author HP
 * @date 2018/5/8
 *
 * 家长提问
 * api/question/add
 */

public class UploadQuestionActivity extends BaseActivity {

    private static final String TAG = UploadQuestionActivity.class.getSimpleName();

    @Bind(R.id.title)
    EditText title;
    @Bind(R.id.content)
    EditText content;

    @Bind(R.id.imageView)
    ImageView imageView;

    @Bind(R.id.submm_btn)
    TextView submm_btn;

    private String file;//文件路径
    private int teacherId;//教师id

    //图片选择工具
    private PhotoSelectUtils mPhotoSelectUtils;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_uploadquestion;
    }

    @Override
    protected void init() {

        teacherId = getIntent().getIntExtra("teacherId",-1);
        StyleUtil.titleBackKey(this, "提问");
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_color));//沉侵式头部
    }


    @OnClick({R.id.imageView,R.id.submm_btn})
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.imageView:
                showPop();
                break;


            case R.id.submm_btn:
                uploadQa();
                break;
        }
    }

    //提交问题
    private void uploadQa() {

        if(TextUtils.isEmpty(title.getText())){
            ToastUtil.show("请输入标题");
            return;
        }

        if(TextUtils.isEmpty(content.getText())){
            ToastUtil.show("请输入问题内容");
            return;
        }

        if(TextUtils.isEmpty(file)){
            ToastUtil.show("请选择图片文件");
            return;
        }

        Map<String,RequestBody> params = new HashMap<>();
        params.put("sign", RequestBody.create(MediaType.parse("multipart/form-data"), "test"));
        params.put("uuid", RequestBody.create(MediaType.parse("multipart/form-data"), "5617222222"));
        params.put("version", RequestBody.create(MediaType.parse("multipart/form-data"), BuildConfig.VERSION_NAME));
        params.put("accessToken", RequestBody.create(MediaType.parse("multipart/form-data"), SePref.getToken()));

        StringBuilder pData = new StringBuilder();
        pData.append("memberId:" + SePref.getId());
        pData.append(",teacherId:" + teacherId);

        pData.append(",title:" + title.getText().toString());
        pData.append(",descr:" + content.getText().toString());

        params.put("requestData", RequestBody.create(MediaType.parse("multipart/form-data"), "{" + pData.toString() + "}"));

        File files = new File(file);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), files);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("files", files.getName(), requestFile);

        // 执行请求
        Call<ResponseBody> call = createCallService(LoginService.class).addQuestion(params,filePart);
        showLoading();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call,
                                   Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "uploadQa data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code") &&
                            "true".equals(jsonObject.getString("responseData"))){
                        ToastUtil.show("问题提交成功");

                        Intent  intent = new Intent(UploadQuestionActivity.this, HomeActivity.class);
                        startActivity(intent);
                        finish();

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d("Upload error:", t.getMessage());
            }
        });

    }

    private void showPop() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .addSheetItem("相机", SheetItemColor.Blue,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                checkPic(true);
                            }
                        })
                .addSheetItem("图库", SheetItemColor.Blue,
                        new OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                checkPic(false);
                            }
                        }).show();
    }


    //选择图片
    private void checkPic(boolean isCamera) {
        if(null == mPhotoSelectUtils){
            mPhotoSelectUtils = new PhotoSelectUtils(UploadQuestionActivity.this);
            mPhotoSelectUtils.setTailor(1, 1, 350, 350);
        }

        if(isCamera){
            mPhotoSelectUtils.startTakeWayByCarema();
        }else {
            mPhotoSelectUtils.startTakeWayByAlbum();
        }

        mPhotoSelectUtils.setTakePictureCallBackListener(new PhotoSelectUtils.takePictureCallBackListener() {
            @Override
            public void successful(boolean isTailor, File outFile, Uri filePath) {
                file = filePath.getPath();
                Log.d(TAG,"filePath.getPath() = " + filePath.getPath());
                Glide.with(UploadQuestionActivity.this).load(filePath).into(imageView);
            }

            @Override
            public void failed(int errorCode, List<String> deniedPermissions) {
                Log.d(TAG,"deniedPermissions = " + deniedPermissions);
            }

        });

    }

    //把本地的onActivityResult()方法回调绑定到对象
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(null != mPhotoSelectUtils) {
            mPhotoSelectUtils.attachToActivityForResult(requestCode, resultCode, data);
        }
    }

    //onRequestPermissionsResult()方法权限回调绑定到对象
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mPhotoSelectUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}
